package cool.taomu.toolkit.utils

class PageUtils {
	long total;
	int requestedPage = 1;
	int pageSize = 10;

	new(int total, int pageSize, int page) {
		this.total = total;
		this.requestedPage = page;
		this.pageSize = pageSize;
	}

	def int calculateTotalPages() {
		if (this.pageSize <= 0) {
			throw new IllegalArgumentException("Page size must be greater than 0.");
		}
		return Math.ceil(this.total as double / pageSize) as int;
	}

	def int validateAndAdjustPageNumber() {
		if (this.requestedPage < 1) {
			return 1; // 如果请求的页码小于1，则返回第一页
		} else if (requestedPage > total) {
			return total > 0 ? total as int : 1; // 如果请求的页码大于总页数，则返回最后一页或第一页（如果没有任何记录）
		} else {
			return requestedPage;
		}
	}

	def int calculateOffset() {
		var adjust = this.validateAndAdjustPageNumber()
		return (adjust - 1) * pageSize;
	}

}
